﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Macds.Core.Serialization
{
    public class Converter
    {
        /// <summary>
        /// This method return a byte array of any object decorated with the attribute [Serializable]
        /// </summary>
        /// <param name="obj">object to be converted</param>
        /// <returns>byte array</returns>
        public static byte[] GetBytesFromObject(object obj)
        {
            MemoryStream memStream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memStream, obj);
            return memStream.GetBuffer();
        }

        /// <summary>
        /// This method return a object from a byte array
        /// </summary>
        /// <param name="data">byte array</param>
        /// <returns>object</returns>
        public static object GetObjectFromBytes(byte[] data)
        {
            MemoryStream memStream = new MemoryStream(data);
            BinaryFormatter formatter = new BinaryFormatter();
            return formatter.Deserialize(memStream);
        }

        /// <summary>
        /// Convert an object to XML
        /// </summary>
        /// <param name="obj">dynamic object</param>
        /// <returns>XML string</returns>
        public static string GetXmlFromObject<T>(T obj)
        {
            StringBuilder sb = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true });
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            serializer.Serialize(writer, obj, ns);
            return sb.ToString();
        }

        /// <summary>
        /// Convert a specific XML schema to its object form
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="type"></param>
        /// <returns>dynamic object</returns>
        public static T GetObjectFromXml<T>(string xml)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringReader stringReader = new StringReader(xml);
            XmlTextReader xmlReader = new XmlTextReader(stringReader);
            T tempObj = (T)serializer.Deserialize(xmlReader);
            xmlReader.Close();
            stringReader.Close();

            return tempObj;
        }
    }
}
